package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.*;
import worklog.dto.ProjectDTO;
import worklog.dto.ResponseDTO;

@WebServlet("/addProject")
public class AddProject extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProjectDB projectDB;
	private ResponseDTO responder = new ResponseDTO();

	public AddProject() {
		super();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		projectDB = new ProjectDB();		
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
		out.print(processRequest(request));
		projectDB.close();
		out.close();
	}

	private String processRequest(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		//TODO: check privileges for adding projects

		int paramLength = request.getParameterMap().size(), projectId;
		String name, tags, archiveStr;
		Boolean archive;
		
		ProjectDTO project = new ProjectDTO();
		if (paramLength == 0) return responder.showError();
		name = request.getParameter("name");
		archiveStr = request.getParameter("archive");
		tags = request.getParameter("tags");
		if (name == null) return responder.showError("Project name is empty");
		if (projectDB.checkProjectName(name)) return responder.showError("Project name already exists");

		project.setName(name);
		if (archiveStr != null) {
			archive = archiveStr.equals("true");
			project.setArchive(archive);
		}
		if (tags != null) project.setTags(tags);
		projectId = projectDB.addProject(project);
		if (projectId != -1) {
			project.setId(projectId);
			return project.toString();
		}
		return responder.showError("DB error");
	}

}
